package com.goodwill.androidtest.annotation;

import android.app.Activity;
import android.view.View;

import java.lang.reflect.Field;

public class ViewInject {
    public static void inject(Activity activity) {

        inject(new ViewFindder(activity), activity);
    }

    public static void inject(View view) {

        inject(new ViewFindder(view), view);
    }

    public static void inject(ViewFindder findder, Object object) {
        Class<?> clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            ViewById viewById = field.getAnnotation(ViewById.class);
            if (viewById != null) {
                int viewId = viewById.value();
                View view = ViewFindder.findViewById(viewId);
                if (view != null) {
                    try {
                        field.set(object, view);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
